package cheme.ProcessEditor.Parts.Streams;

import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.AbstractEditPolicy;

import cheme.ProcessEditor.Figures.Util.MoveTagCmd;
import cheme.ProcessEditor.Figures.Util.TagLocator;

public class TagMoveEditPolicy extends AbstractEditPolicy
{
	@Override
	public Command getCommand(Request request)
	{
		Command cmd = null;
//		try
//		{
			if(request.getType().equals("MoveTagRequest"))
			{
				//System.out.println("TagMoveEditPolocy " + request.getType());
				cmd = createMoveCmd((MoveTagRequest)request);
			}
			else
			{
				cmd = super.getCommand(request);
			}
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}
//		finally
//		{
			return cmd;
//		}
	}
	
	protected Command createMoveCmd(MoveTagRequest request)
	{
		Dimension delta = request.getDelta();
		int newX = startGapX + delta.width;
		int newY = startGapy + delta.height;
				
		return new MoveTagCmd(request.getSource().getFigure(), 
								request.getSource().getLocator(), 
								newX, newY);
	}
		
	int startGapX = 0;
	int startGapy = 0;
	
	Dimension startGap = null;
	
	@Override
	public void showSourceFeedback(Request request)
	{
		if(!(request instanceof MoveTagRequest))
		{
			return;
		}
		
		MoveTagRequest req = (MoveTagRequest)request;
		
		if(null == startGap)
		{
			startGapX = req.getLocator().getXGap();
			startGapy = req.getLocator().getYGap();
			startGap = new Dimension(startGapX, startGapy);
		}
		
		Dimension delta = req.getDelta();
		int newX = startGap.width + delta.width;
		int newY = startGap.height + delta.height;
		
		relocateFigure(req.getLocator(), req.getFigure(), newX, newY);
	}
	
	@Override
	public void eraseSourceFeedback(Request request)
	{
		if(!(request instanceof MoveTagRequest))
		{
			return;
		}
		
		MoveTagRequest req = (MoveTagRequest)request;
		relocateFigure(req.getLocator(), req.getFigure(), startGapX, startGapy);
		
		startGap = null;
	}
	
	void relocateFigure(TagLocator locator, Figure figure, int newX, int newY)
	{
		locator.setXGap(newX);
		locator.setYGap(newY);
		locator.relocate(figure);
		figure.getParent().revalidate();
	}
}
